import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Home from '@/components/home/Home'
import Food from '@/components/home/Food'
import Login from '@/components/Login'
import User from '@/components/user/User'
import UserInfo from '@/components/user/userInfo/UserInfo'
import Order from '@/components/order/Order'
import editbirthday from '@/components/user/userInfo/EditUserDate'
import editUserName from '@/components/user/userInfo/EditUserName'
import Address from '@/components/user/userInfo/Address'
import store from '@/store/store.js'
import * as types from '@/store/types'
import Notfound from '@/components/global/Notfound';

Vue.use(Router)
const routes = [{
        path: '/',
        name: 'Home',
        component: Home,
        children: [{
            name: 'Food',
            path: 'food',
            component: Food,
            // children: [
            //     { name: 'editbirthday', path: 'editbirthday', component: editbirthday },
            //     { name: 'editUserName', path: 'editName', component: editUserName },
            //     { name: 'editUserAddr', path: 'editAddr', component: Address },
            // ]
        }, ],
        meta: {
            // requiresAuth: true
        }
    }, {
        path: '/login',
        name: 'Login',
        component: Login
    }, {
        path: '/user',
        name: 'User',
        component: User,
        children: [{
            name: 'UserInfo',
            path: 'userInfo',
            component: UserInfo,
            children: [
                { name: 'editbirthday', path: 'editbirthday', component: editbirthday },
                { name: 'editUserName', path: 'editName', component: editUserName },
                { name: 'editUserAddr', path: 'editAddr', component: Address },
            ]
        }, ],
        meta: {
            requiresAuth: true
        }
    }, {
        path: '/order',
        name: 'Order',
        component: Order,
        meta: {
            requiresAuth: true
        }
    },
    {
        path: '*',
        component: Notfound,
        meta: {
            // requiresAuth: true
        }
    }
];

const router = new Router({
    mode: 'history',
    routes
})

if (window.localStorage.getItem("token")) {
    store.commit(types.LOGIN, window.localStorage.getItem('token'))
}

router.beforeEach((to, from, next) => {
    // console.log(from);
    console.log(to);
    let token = window.localStorage.getItem('token')
    console.log("token:" + token);

    if (to.matched.some(record => record.meta.requiresAuth)) {
        if (store.state.token) {
            next()
        } else {
            store.commit(types.LOGIN, window.localStorage.getItem('token'), to.fullPath)
            next({
                path: '/login',
                query: { redirect: to.fullPath }
            })
        }
    } else {
        next()
    }
})

export default router